import json

from apps.common.base.serializers import *
from apps.merchant.item.models import *
from apps.merchant.sku.serializers import Sku, SkuModelSerializer


class ItemBaseSerializer(BaseSerializer):
    class Meta:
        model = Item
        fields = "__all__"


class ItemModelSerializer(BaseSerializer):

    lesseeModel = serializers.SerializerMethodField()
    def get_lesseeModel(self, obj):
        try:
            return {'id': obj.lessee.id, 'name': obj.lessee.name}
        except:
            return {}

    activityModel = serializers.SerializerMethodField()
    def get_activityModel(self, obj):
        try:
            return {'id': obj.activity.id, 'name': obj.activity.name, 'key': obj.cate.key}
        except:
            return {}

    cateModel = serializers.SerializerMethodField()
    def get_cateModel(self, obj):
        if obj.cate:
            return {'id': obj.cate.id, 'name': obj.cate.name, 'key': obj.cate.key}
        else:
            return {}

    suggestSellingPrice = serializers.SerializerMethodField()

    def get_suggestSellingPrice(self, obj):
        skus = obj.item_sku.all().order_by('sellingPrice')
        if skus.exists():
            suggestSellingPrice = str(skus.first().sellingPrice)
            return suggestSellingPrice
        else:
            return ''

    coverUrl = serializers.SerializerMethodField()

    def get_coverUrl(self, obj):
        if obj.coverPhotos:
            coverPhotos = json.loads(obj.coverPhotos)
            if len(coverPhotos) > 0:
                return coverPhotos[0]

        return ''

    coverPhotoList = serializers.SerializerMethodField()

    def get_coverPhotoList(self, obj):
        try:
            coverPhotoList = json.loads(obj.coverPhotos)
            if len(coverPhotoList) > 0:
                return coverPhotoList
        except:
            return []

    skuList = serializers.SerializerMethodField()
    def get_skuList(self, obj):
        skus = obj.item_sku.all()
        if skus.exists():
            return SkuModelSerializer(skus, many=True).data
        else:
            return []

    class Meta:
        model = Item
        fields = "__all__"
